
/**
 * 车辆信息
 */
var iFrameName = this.name;
$(function(){
	Vehicle.init();
	window.parent.global.ajaxLoading.close(1000);
});
var Vehicle = {
	init: function(){
		Vehicle.initInput();
		Vehicle.chooses ="";
		Vehicle.sub_url ="";
		Vehicle.queryW();
		Vehicle.tbTerminalParamsLoad = false;
		Vehicle.initEvent();
		this.initVehicleList();
		placeholders("#queryVehicelNo");
	},
	initInput : function(){
		var areaTool =$('#queryArea').combotree({
			url:appCtx + "/system/common/queryAreaTree.html",
			valueField: 'id',
            textField: 'text',
            method: 'post',
            editable : true,
            collapseAll : true,
            onSuccess : function(data){
            	
            },            
            loadFilter: function(data){
            	 data.unshift({ id: '', text: '请选择所属区域', selected: "selected" });
                 return data;
    		},
    		onLoadSuccess: function (data) {
    			$('#queryArea').combotree('tree').tree("collapseAll");
    			$('#queryArea').combotree('setValue','')
         	}
			
		});
		areaTool.combogrid('textbox').keyup(function(event) {
			$('#queryArea').combotree('tree').tree("search", $(this).val());
		});
		$('#queryTrade').combobox({
			url:appCtx + "/system/common/queryAllTrade.html",
			valueField: 'id',
            textField: 'text',
            editable : true,
            loadFilter: function(data){
            	 data.unshift({ id: '', text: '请选择所属行业', selected: "selected" });
                 return data;
    		}
		});
		$('#queryPlatform').combobox({
			url:appCtx + "/system/common/queryAllPlatform.html",
			valueField: 'id',
            textField: 'text',
            editable : true,
            loadFilter: function(data){
            	 data.unshift({ id: '', text: '请选择接入平台', selected: "selected" });
                 return data;
    		}
    		
		});
		
		/*$('#queryEnterprise').combobox({
			url:appCtx + "/system/common/queryEnterprise.html",
			valueField: 'ID',
            textField: 'text',
            editable : true,
            loadFilter: function(data){
            	 data.unshift({ ID: '', text: '请选择所属业户' ,selected: "selected"});
                 return data;
    		},
    		onLoadSuccess : function(data){
    		}
    		
		});*/
		$('#queryEnterprise').select2({
    		theme: "default",
 	        allowClear: true,
 	        placeholder: "请选择所属业户",
 	        ajax:{
 	            url:appCtx + "/report/alarmSyn/queryEntAndPlatByRole.html?time="+ new Date().getTime(),
 	            dataType:"json",
 	            delay:250,
 	           async : true,
 	            data:function(params){
 	                return {
 	                    name: params.term,
 	                    page: params.page || 1
 	                };
 	            },
 	            cache:true,
 	            processResults: function (res, params) {
 	          
 			    	if(res){
 			    		var options = [];
 			    		var option = {"id":" ", "text":"请选择所属业户"};
 			    		options.push(option);
 	    				$.each(res,function(index,obj) {
 	    					var option = {"id":obj.entId, "text":obj.entName};
     	                    options.push(option);
 	    				});
     	                return {
     	                	results: options,
     	                    pagination: {
     	                        more:false
     	                    }
     	                };
 			    	}
 	            },
 	            escapeMarkup: function (markup) { return markup; },
 	            minimumInputLength: 1
 	        }
    	});
		$('#queryTerminal').combobox({
			url:appCtx + "/system/common/queryTeminalType.html",
			valueField: 'ID',
            textField: 'text',
            editable : true,
            loadFilter: function(data){
            	 data.unshift({ ID: '', text: '请选择终端类型' ,selected: "selected"});
                 return data;
    		},
    		onLoadSuccess : function(data){
    		}
    		
		});
		/*var vehicleType = $('#queryVehicleKind').combotree({
			url:appCtx + "/system/common/queryVehicleTypeTree.html",
			valueField: 'id',
            textField: 'text',
            editable : true,
            collapseAll : true,
            loadFilter: function(data){
            	  data.unshift({ id: '', text: '请选择车辆类型', selected: "selected" });
                  return data;
    		},
    		onLoadSuccess: function (data) {
    			$('#queryVehicleKind').combotree('tree').tree("collapseAll");
    			$('#queryVehicleKind').combotree('setValue','')
         	}
		});
		vehicleType.combogrid('textbox').keyup(function(event) {
			$('#queryVehicleKind').combotree('tree').tree("search", $(this).val());
		});*/
	},
	queryW : function(){
		var winW = $('body').width();
		$('.querys').width(winW);
	},
	initEvent: function(){
		$('#queryBtn').click(function(){
			Vehicle.vehicleListReload();
		});
		
		$("a[name='addVehicleBtn']").click(function(){
			var url = appCtx + "base/vehicleManager/initVehicleForm.html";
			window.parent.doDataDialog("insert","增加车辆",iFrameName,"VehicleForm.saveVehicle()", "Vehicle.vehicleListReload()",url);
			$('#dataModal').addClass('addDataModalClass');
			
		});
		
		$("a[name='updateVehicleBtn']").click(function(){
			Vehicle.updateVehicle();
		});
		
		$("a[name='delVehicleBtn']").click(function(){
			Vehicle.delVehicles();
		});
		
		$("a[name='cancelVehicleBtn']").click(function(){
			Vehicle.cancelVehicles();
		});
		
		$("a[name='exportVehicleBtn']").click(function(){
			Vehicle.exportVehicle();
		});
		
		$("a[name='viewDetails']").click(function(){
			Vehicle.viewDetails();
		});
		
		$("a[name='importVehicleBtn']").click(function(){
			Vehicle.importVehicle();
		});
		$("#confirmImport").on("click",function(){
			
	    	Vehicle.importComfirm(); 
	    	console.log(1111);
	    });
		$("#download").on("click",function(event){
			Vehicle.downLoad(event); 
			
		});
		$("a[name='synVehicleBtn']").click(function(){
			Vehicle.synVehicle();
		});
	},
	
	viewDetails : function(){
		//var me = this;
		var checkedIds = $("#tbVehicles").getCheckedRows();
		if(checkedIds.length<1){
			window.parent.global.ajaxLoading.pop('请选择要查看的车辆!',false,3000);
			return;
		}
		if(checkedIds.length>1){
			window.parent.global.ajaxLoading.pop('只能选择一条数据!',false,3000);
			return;
		}
		
		var url = appCtx + "base/vehicleManager/viewVehicleDetail.html?vehicleId="+checkedIds[0];
		window.parent.doDataDialog("detail","车辆详情",iFrameName,"Vehicle.vehicleListReload()", "Vehicle.vehicleListReload()",url);
	},
	
	getParams: function(){
		var vehicleNo = $('#queryVehicelNo').val();
		var enterpriseId = $.trim($('#queryEnterprise').val());
		var tradeId = $('#queryTrade').combobox('getValue');
		var areaId = $('#queryArea').combobox('getValue');
		var platformId = $('#queryPlatform').combobox('getValue');
		var teminalId = $('#queryTerminal').combobox('getValue');
		if(vehicleNo == "请输入车牌号码"){
			vehicleNo ="";
		}
		var params = [ {
			name : 'vehicleNo',
			value : vehicleNo
		},{
			name : 'enterpriseId',
			value : enterpriseId
		},{
			name : 'tradeId',
			value : tradeId
		},{
			name : 'areaId',
			value : areaId
		},{
			name : 'platformId',
			value : platformId
		},{
			name : 'teminalId',
			value : teminalId
		}];
		return params;
	},
	vehicleListReload: function(){
		$("#tbVehicles").flexOptions({
			newp :1,// 设置起始页
			url : appCtx + "base/vehicleManager/loadAllVehicles.html",
			params : Vehicle.getParams()
		}).flexReload();
	},
	getColumn: function(){
		return [{
			display : '车牌号码',
			name : 'vehicleNo',
			width : 80,
			sortable : true,
			align : 'left'
		},{
			display : '车牌颜色',
			name : 'vColor',
			width : 60,
			sortable : true,
			align : 'left'
		},{
			 name: 'colorId',
             hide: true,
		},{
			display : '所属业户',
			name : 'enterpriseName',
			width : 200,
			sortable : true,
			align : 'left',
			showTitle:true
		},{
			display : '接入平台',
			name : 'platformName',
			width : 190,
			sortable : true,
			align : 'left',
			showTitle:true
		},{
			display : '所属行业',
			name : 'tradeName',
			width : 120,
			sortable : true,
			align : 'left',
			showTitle:true
		},{
			display : '所属区域',
			name : 'areaName',
			width : 120,
			sortable : true,
			align : 'left',
			showTitle:true
		},{
			display : '终端类型',
			name : 'teminalName',
			width : 120,
			sortable : true,
			align : 'left',
			showTitle:true
		},{
			display : "经营范围",
			name : "bussinessScope",
			width : 120,
			align : 'left',
			showTitle:true
		},{
			display : '道路运输证号',
			name : "road_transport_num",
			width : 120,
			sortable : true,
			align : 'left',
			showTitle:true
		},{
			display : '证件有效期',
			name : "validTime",
			width : 240,
			sortable : true,
			align : 'left',
			showTitle:true
		},{
			display : "营运状态",
			name : "status",
			width : 120,
			align : 'left',
			showTitle:true
		},{
			display : "第一次定位",
			name : "firstOnline",
			width : 120,
			align : 'left',
			showTitle:true
		/*},{
			display : "是否在线",
			name : "online",
			width : 120,
			align : 'left',
			showTitle:true*/
		},{
			display : '联系人',
			name : 'linkMan',
			width : 120,
			sortable : true,
			align : 'left'
		},{
			display : '联系号码',
			name : 'telePhone',
			width : 120,
			sortable : true,
			align : 'left'
		},{
			display : '短信提醒',
			name : 'sms',
			width : 120,
			sortable : true,
			align : 'left',
		},{
			display : '同步运政',
			name : 'hasSync',
			width : 120,
			sortable : true,
			align : 'left'
		}];
	},
	initVehicleList: function(){
		//var me = this;
		$("#tbVehicles").flexigrid({
			url : appCtx + "base/vehicleManager/loadAllVehicles.html",
			dataType : 'json',
			params : Vehicle.getParams(),
			colModel : Vehicle.getColumn(),
			resizable : false,
			sortname : "id",// 第一次加载数据时排序列
			sortorder : "desc",// 第一次加载数据时排序类型
			usepager : true,// 是否分页，默认为true。
			showToggleBtn : false,
			showTableToggleBtn : true,// 是否显示收起/打开按钮,默认不显示。
			useRp : true,// 是否可以动态设置每页显示的结果数，默认为false。
			rp : 10,// 每页记录数，默认为10
			checkbox : true,// 是否要多选框,默认为false。
			rowId : 'id',// 多选框绑定行的id,只有checkbox : true时才有效。
			singleSelect : false,
			width : 'auto',
			height : nav.whiceH[0] - 155,
			
		// 表格高度
		});
	},
	
	
	
	updateVehicle: function(){
		//var me = this;
		var checkedIds = $("#tbVehicles").getCheckedRows();
		if(checkedIds.length<1){
			window.parent.global.ajaxLoading.pop('请选择要修改的数据!',false,3000);
			return;
		}
		if(checkedIds.length>1){
			window.parent.global.ajaxLoading.pop('只能选择一条数据!',false,3000);
			return;
		}
		
		var url = appCtx + "base/vehicleManager/initUpdateVehicleForm.html?vehicleId="+checkedIds[0];
		window.parent.doDataDialog("update","修改车辆",iFrameName,"VehicleForm.saveVehicle()", "Vehicle.vehicleListReload()",url);
	},
	synVehicle: function(){
		//var me = this;
		var checkedIds = $("#tbVehicles").getCheckedRows();
		if(checkedIds.length<1){
			window.parent.global.ajaxLoading.pop('请选择要修改的数据!',false,3000);
			return;
		}
		if(checkedIds.length>1){
			window.parent.global.ajaxLoading.pop('只能选择一条数据!',false,3000);
			return;
		}
		window.parent.doConfirm("确定要同步运政车辆数据吗?",iFrameName,"Vehicle.synDataVehicleConfirm()");
	},
	synDataVehicleConfirm :function(){
		var checkedIds = $("#tbVehicles").getCheckedRows();
		$.ajax({
	        type: 'post',
	        async: false,
	        url: appCtx + "base/vehicleManager/synVeicleInfo.html",
			data:{
					vehicleIds : checkedIds.toString()
				 },
	        cache: false,
	        dataType : "JSON",
	        success: function (data) {
	        	var msg = "";
				if(data.code == "0"){
					$("#tbVehicles").flexReload();
					window.parent.global.ajaxLoading.pop('同步成功！',false,1000);
					return;
				}else if(data.code == "1"){
					window.parent.global.ajaxLoading.pop('运政无数据！',false,1000);
				}else{
					window.parent.global.ajaxLoading.pop('同步失败！',false,1000);
					
				}
				
	        }
	    });	
	},
	delVehicles: function(){
		//var me = this;
		var checkedIds = $("#tbVehicles").getCheckedRows();
		if(checkedIds.length<1){
			//window.parent.showVelidateModal("请选择要删除的数据！");
			window.parent.global.ajaxLoading.pop('请选择要删除的数据!',false,3000);
			return;
		}
		window.parent.doConfirm("确定要删除吗？删除后将无法恢复！",iFrameName,"Vehicle.deleteVehicleConfirm()");
	},
	deleteVehicleConfirm: function(){
		var checkedIds = $("#tbVehicles").getCheckedRows();
		var vcolor = [];
		 $('#tbVehicles').find('input').each(function () {
             var checked = $(this).attr("checked");
             var tdArr = $(this).parent().parent().children();
             if (typeof (checked) != "undefined") {
            	 vcolor.push(tdArr.eq(3).find('div').html());
             }
         });
		
		$.ajax({
	        type: 'post',
	        async: false,
	        url: appCtx + "base/vehicleManager/delVehicle.html",
			data:{
					vehicleIds : checkedIds.toString(),
					vehicleColor : vcolor.toString()
				 },
	        cache: false,
	        dataType : "JSON",
	        success: function (data) {
	        	var msg = "";
				if(data.code == "0"){
					$("#tbVehicles").flexReload();
					window.parent.global.ajaxLoading.pop('删除成功！',false,1000);
					return;
				}else{
					msg = "删除失败！";
				}
				$("#validateContentText").html(msg);
				$("#velidateModal").modal("show");
	        }
	    });	
	},
	cancelVehicles:function(){
		var checkedIds = $("#tbVehicles").getCheckedRows();
		if(checkedIds.length<1){
			//window.parent.showVelidateModal("请选择要删除的数据！");
			window.parent.global.ajaxLoading.pop('请选择要注销的数据!',false,3000);
			return;
		}
		window.parent.doConfirm("确定要注销吗？",iFrameName,"Vehicle.cancelVehicleConfirm()");
	},
	cancelVehicleConfirm: function(){
		var checkedIds = $("#tbVehicles").getCheckedRows();
		var vcolor = [];
		 $('#tbVehicles').find('input').each(function () {
             var checked = $(this).attr("checked");
             var tdArr = $(this).parent().parent().children();
             if (typeof (checked) != "undefined") {
            	 vcolor.push(tdArr.eq(3).find('div').html());
             }
         });
		
		$.ajax({
	        type: 'post',
	        async: false,
	        url: appCtx + "base/vehicleManager/cancelVehicle.html",
			data:{
					vehicleIds : checkedIds.toString(),
					vehicleColor : vcolor.toString()
				 },
	        cache: false,
	        dataType : "JSON",
	        success: function (data) {
	        	var msg = "";
				if(data.code == "0"){
					$("#tbVehicles").flexReload();
					window.parent.global.ajaxLoading.pop('注销成功！',false,1000);
					return;
				}else{
					msg = "注销失败！";
				}
				$("#validateContentText").html(msg);
				$("#velidateModal").modal("show");
	        }
	    });	
	},
	exportComfirm:function(){

		var me = this;
		var p=window.parent;
		
		var options = $("#tbVehicles").getOptions();
		//总记录数
		var total = options.total;
		//开始页数
		var StartPage=window.parent.$("#StartPageIndex").val();
		//结束页数
		var EndPage=window.parent.$("#EndPageIndex").val();
		var validate=true;
		var msg="";
		if(!StartPage || StartPage==0){
			msg+="起始页不能为空或者0";
			validate=false;
		}
		if(!EndPage || EndPage==0){
			msg+="结束页不能为空或者0";
			validate=false;
		}
		
		if(StartPage && EndPage &&EndPage<StartPage){
			msg+="结束页要大于起始页";
			validate=false;
		}
		if(!validate){
			p.ajaxLoading(msg,false,2000);
			return;
		}
		p.$('#exportModal').modal('hide');
		p.ajaxLoading("正在导出,请稍后.....",true,2000);
		//每页大小
		var pagesize = options.rp;
		
		//获取导出的参数
		var exportParams = options.exportParams;
		if((EndPage - StartPage + 1) * pagesize > 60000&&total>60000)
		{
			window.parent.global.ajaxLoading.pop("最多只能导出60000条数据", true, 2000);
			return
		}
		
        var column = Vehicle.getColumn();
        var exportColumns = new Array();
        for(var i=0;i<column.length;i++){
        	if(column[i].hide!=true &&column[i].name !="operation" && column[i].name !="noColor" && column[i].name !="registrationNoKindName"){
        		exportColumns.push(column[i]);
        	}
        }
		var header1 = JSON.stringify(exportColumns);
		var colModelList=new Array();//表头
		colModelList.push(header1);
		var colModel= $.toJSON(colModelList);
		
		var vehicleNo = $("#queryVehicelNo").val();
		var areaId = $("#queryArea").combobox('getValue');
		var platformId = $("#queryPlatform").combobox('getValue');
		var tradeId = $("#queryTrade").combobox('getValue') ;
		var enterpriseId = $.trim($('#queryEnterprise').val()); 
		
		var paramsGrid =  {
				colModel:colModel,
				vehicleNo:vehicleNo,
				title :"车辆信息",
				areaId : areaId,
				platformId : platformId,
				tradeId : tradeId,
				enterpriseId : enterpriseId,
				imgsrc : null,
				StartPage : StartPage,
				EndPage : EndPage,
				pagesize : pagesize
		};
		
		post(appCtx + "base/vehicleManager/exportVehicles.html",paramsGrid);
	},
	/**
	 * 导出车辆
	 */
	exportVehicle: function(){
		var p=window.parent;
		var options = $("#tbVehicles").getOptions();
		var total = options.total;
		if(total==0){
			p.ajaxLoading("无导出数据",false,2000);
			return;
		}
		var pages = options.pages;
		//设置默认的开始结束页
		window.parent.$("#StartPageIndex").val(1);
		window.parent.$("#EndPageIndex").val(pages);
		window.parent.doExportModal("导出车辆信息",iFrameName,"Vehicle.exportComfirm()");   
		
	},
	contains: function(valArrays,val){
		for(var i = 0;i < valArrays.length;i++){
			if(valArrays[i] == val){
				return true;
			}
		}
		return false;
	},
	
	
	/** 
	 * 从表格中的选中列中判断终端类型是否唯一
	 * index 为td的序号，从0开始
	 * **/
	isTerminalKindFormGrid: function(tableId,index){
		var arrays = $("#" + tableId).getSelectedRows();
		var valArrays = [];
		for(var i = 0; i < arrays.length;i++){
			var val = $.trim($(arrays[i].context.cells[index]).text());
			if(!Vehicle.contains(valArrays,val)){
				valArrays.push(val);
			}
		}
		if(valArrays.length == 1){//状态值唯一
			return true;
		}
		return false;
	},
	/**
	 * 导入业户信息
	 */
	importVehicle: function(){
		Vehicle.doImportModal("导入车辆信息",iFrameName);  
	},
	
	doImportModal:function(msg,iFrameName,callback){
//		$("#confirmImport").on("click",function(){
//	    	Vehicle.importComfirm(); 
//	    });
//	    $("#download").on("click",function(event){
//	    	event.preventDefault(); // 使a自带的方法失效
//	    	$.ajax({
//		        type: 'post',
//		        async: false,
//		        url: appCtx + "base/vehicleManager/importVehilceExcelTemplate.html",
//		        cache: false,
//		        dataType : "JSON",
//		        success: function (data) {
//		        	var msg = "";
//					if(data.code == "0"){
//						window.parent.global.ajaxLoading.pop('模板下载成功！',false,1000);
//					}else if(data.code == "1"){
//						window.parent.global.ajaxLoading.pop('模板下载失败！',false,1000);
//					}
//		        }
//		    });	
//	    });
	    $("#importModalLabel").html(msg);
		$("#importModal").modal('show');
	},
	downLoad : function(event){
		event.preventDefault(); // 使a自带的方法失效
//    	$.ajax({
//	        type: 'post',
//	        async: false,
//	        url: appCtx + "base/vehicleManager/importVehilceExcelTemplate.html",
//	        cache: false,
//	        dataType : "JSON",
//	        success: function (data) {
//	        	var msg = "";
//				if(data.code == "0"){
//					window.parent.global.ajaxLoading.pop('模板下载成功！',false,1000);
//				}else if(data.code == "1"){
//					window.parent.global.ajaxLoading.pop('模板下载失败！',false,1000);
//				}
//	        }
//	    });	
    	post(appCtx + "base/vehicleManager/importVehilceExcelTemplate.html",null);
	},
	importComfirm :function(){
		window.parent.global.ajaxLoading.pop('正在导入车辆信息,请稍后......',true);
		$.ajaxFileUpload({
            type: "post",
            url: appCtx + "base/vehicleManager/importVehicle.html",
            fileElementId: "uploadVehicle",
            dataType: 'json',
            data: {
                "fileUploadId": "uploadVehicle"
            },
            success: function (data, status) {
                var msg = eval("(" + data + ")");
                var message = "";
                if (msg.data == "") {
                    message = "导入车辆数据成功!";
                }
                else {
                    message = msg.data;
                }
                $("#tbVehicles").flexReload();
                window.parent.global.ajaxLoading.close();
                Vehicle.showVelidateModal(message);
                $("#uploadForm")[0].reset();
               
            },
            error: function (data, status, e) {
            	
            }
        });
	},
	showVelidateModal:function(msg){
		$("#velidateModal").modal('show');
		$("#contentText").html(msg);
	}
};


